<?php

/*
 * $service: the url of api
 * $json: requestJSON
 */

function call_workflow_service_api($service, $json, $method = 'post', $parameter_prefix=NULL) {//return;
    //if not login in CAS return
    if(empty($_SESSION['phpCAS']['pgt'])){
        $url = INTERACT_GATEWAY_API. "/enquiry";
        echo $url;
        echo '<br>/';
        $addtional_header = sprintf('Authorization: Basic %s',base64_encode('AutoImport@pgcrown.com:'.'auvgpat4'));
//        $addtional_header = sprintf('Authorization: Basic %s',base64_encode('mark sg:'.'password'));
        $arg=array();
        if($parameter_prefix == TRUE){
            $data = $json;
        }else{
            $data = 'requestJSON=' . $json;
        }
        $myrs = mycurl($url,$method,$arg,$data,1,$addtional_header,true);
        $result['http_code'] = $myrs['header']['http_code'];
        $result['body'] = $myrs['body'];
        return $result;
    }
  $result = array();
  if (function_exists('cas_phpcas_init')) {
    cas_phpcas_init();
    
    phpCAS::forceAuthentication();
    $err_code = '';
    $err_msg = t('Retrieve PT error');
    $pt = phpCAS::retrievePT($service, $err_code, $err_msg);
    //error_log($service);
    //error_log($pt);
    $arg = array('ticket' => $pt);
    if($parameter_prefix == TRUE){
      $data = $json;
    }else{
      $data = 'requestJSON=' . $json;
    }
    
    //error_log($data);
    $myrs = mycurl($service, $method, $arg, $data, 1, '', true);
    $header = $myrs['header'];
    $body = $myrs['body'];


    $result = array();
    if (isset($header['http_code']) && $header['http_code'] === 200) {
      $result['http_code'] = $header['http_code'];
      $result['body'] = $body;
    } else {
      $result['http_code'] = $header['http_code'];
      $result['body'] = $body;
    }
    
  }
  return $result;
}

function create_workflow_startProcess($node, $submission) {
  global $user;

  $service = WORKFLOW_SERVICE_API . 'startProcess.ws';
  $module_code=$node->field_form_type['und'][0]['value'];
  //$modeule_code = 'if';
  $workflow_unique = SYSTEM_CODE . '_' . $module_code . '_' . $node->nid;
  $condition = array();
  $wf_private_process_def_id = get_process_mapping_by_workflow_unique($workflow_unique, $condition);
  //$wf_private_process_def_id= "36" ; // hard
  $node->wf_private_process_def_id = $wf_private_process_def_id; //print_r($wf_private_process_def_id);die;
  $userSwimlaneArray = get_swimlanes_by_role($user,array('initate_flag'=>1));

  $json_array = array();
  $json_array['userName'] = $user->name;
  $json_array['userSwimlaneKeys'] = implode(",", $userSwimlaneArray);
  $json_array['privateProcessDefId'] = $wf_private_process_def_id;
  //$json_array['variables']['outCome'] = "flow2";
  //$json_array['variables']['statusCode'] = "initiated";
  $json = json_encode($json_array); 
  //error_log('startProcess:'.print_r($json,1));
  $api_result = call_workflow_service_api($service, $json); 
  //error_log('startProcess:'.print_r($api_result,1));
  $result = json_decode($api_result['body'], true);
  $handle_result = _handle_startProcess_result($result, $node, $submission);
  return $handle_result;
}

function _handle_startProcess_result($result, $node = NULL, $submission = NULL) {
  global $user;
  module_load_include('inc', 'webform_workflow', 'webform_workflow.function');


  $return_code = $result['ResponseStatusInfo']['StatusCode'];
  if ($return_code == 200) {
    $eventList = isset($result['eventList']) ? $result['eventList'] : array();
    $processInstanceId = isset($result['processInstanceId']) ? $result['processInstanceId'] : '';
    $statusCode = isset($result['statusCode']) ? $result['statusCode'] : '';
    $start_trans_key=isset($result['transitionId'])?$result['transitionId'] : 'StartToDraft';
    //=========================== do eventHandler =============================
    if ($eventList) {
      foreach ($eventList as $key => $list) {
        $function = $list['eventHandler'];
        $parameters = $list['parameters'];
        if (function_exists($function)) {
          $function($parameters, $node, $submission);
        }
      }
    }
    //======================= end do eventHandler =============================
    //======================== create a mapping ===============================
    $entity = new stdClass();
    $entity->instance_id = $processInstanceId;
    $entity->entity_id = $submission->sid;
    $entity->wf_private_process_def_id = $node->wf_private_process_def_id;
    $entity->status_code = $statusCode;
    $entity->trans_key=$start_trans_key;
   
    drupal_write_record('workflow_instance_entity_mapping', $entity);
    //======================= end create a mapping  ===========================
    return true;
  } else {
    drupal_set_message($result['ResponseStatusInfo']['StatusMessage'], 'error');
    return false;
  }
}

function create_workflow_getActionOutcomes($node, $submission) { 
  $result=get_action_outcome_from_wfe($node,$submission);  
  $handle_result = _handle_getActionOutcomes_result($result, $node, $submission);
  return $handle_result;
}

function _handle_getActionOutcomes_result($result, $node = NULL, $submission = NULL) {
 drupal_add_js(drupal_get_path('module', 'webformview') . '/js/jquery.validate.js');
 drupal_add_css(drupal_get_path('module', 'webform_submission_history').'/css/pop.css');
 drupal_add_js(drupal_get_path('module', 'webform_submission_history') . '/js/bootstrap-modal.js');
 
  global $user;
  //module_load_include('inc', 'webform_workflow','webform_workflow.function');
  module_load_include('inc', 'webform_workflow', 'webform_workflow.lib');
  $form = '';
  $form['#attributes']=array(
      'name'=>'within_commbox_form',
  ); 
  $form['#tree']=true;
  $return_code = $result['ResponseStatusInfo']['StatusCode'];
  if ($return_code == 200) {
    $actionList = isset($result['actionList']) ? $result['actionList'] : array();
    $privateProcessDefId = isset($result['privateProcessDefId']) ? $result['privateProcessDefId'] : '';
    $processInstanceId = isset($result['processInstanceId']) ? $result['processInstanceId'] : '';   
    /*[begin] add by kale @2013-02-20 add comment&edeit button*/
    //echo $actionList[0]['editableFlag'];
    $editable=isset($actionList[0]['editableFlag']) && $actionList[0]['editableFlag']=='1'?$actionList[0]['editableFlag']:false;
    $form['nid']=array(
        '#type'=>'hidden',
        '#value'=>$node->nid,
    );
    $form['sid']=array(
        '#type'=>'hidden',
        '#value'=>$submission->sid,
    );
   
    $form['comment'] = array(
        '#prefix' => '<div class="modal" id="comment_box" style="width:400px;"><div class="modal-header"><h3>Comment</h3><a data-dismiss="modal" class="icon-btn big-icon-btn"><i class="kicon-close"></i></a></div><div class="modal-body">',
        '#suffix' => '</div></div>',
        '#weight' => '-50',
    );
  
  $form['submit']=array(
        '#prefix' => '<div class="form-actions form-wrapper mt10">',
        '#suffix' => '</div>',
        '#weight' => '-50',
    );
   if($editable){     
      $form['submit']['edit']=array(
          '#type'=>'submit',
          '#value'=>t('Edit'),
      );
    }   
    $form['comment']['content'] = array(
        '#title' => t('Comment'),
        '#type' => 'textarea',
        '#cols' => 40,
        '#rows' => 3,
        '#resizable' => FALSE,
        '#weight' => 0,
        '#default_value' => '',
        '#attributes' => array(
            'for'=>$form['#attributes']['name'],
           // 'class' => array('required'),
        //'name'=>'comment',
        ),
    );
    $form['comment']['btn'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#weight' => 1,
         '#attributes' => array(
            'for'=>$form['#attributes']['name'],
          ),
    );
  
    /*[end] add by kale @2013-02-20 add comment&edeit button*/
   
    //=========================== do actionList =============================
    if ($actionList) {
      foreach ($actionList as $key => $list) {
        $status_code = isset($list['statusCode']) ? $list['statusCode'] : '';
        //$status_code = ''; //hard code;
        $action_status_list=get_action_status_by_transition(array('wf_private_process_def_id'=>$privateProcessDefId));
        foreach ($list['outComes'] as $k => $outComes) {
         // $btn_value = get_action_status_by_transition($privateProcessDefId, $outComes['transitionId'], $status_code);
          $btn_value=$action_status_list[$outComes['transitionId']]['action_name'];          
          $btn_attr=array('data-toggle'=>'modal','href'=>'#comment_box');
          $form['submit'][$outComes['targetName']] = array(
            '#type' => 'submit',
            //'#value' => $outComes['transitionId'] ,
            '#value' => $btn_value,             
          );
        //  if(isset($outComes['targetActionCommentRequired']) && strtoupper($outComes['targetActionCommentRequired'])=='TRUE'){
            $form['submit'][$outComes['targetName']]['#attributes']=$btn_attr;
         // }
          $form['tsId_' . $btn_value] = array(
            '#type' => 'hidden',
            '#value' => $outComes['transitionId'],
          );
          $form['comment_required'][$btn_value]=array(
              '#type'=>'hidden',
              '#value'=>isset($outComes['targetActionCommentRequired']) && strtoupper($outComes['targetActionCommentRequired'])=='TRUE'?1:0,
          );
          $form['targetId'][$btn_value]=array(
              '#type'=>'hidden',
              '#value'=>$outComes['targetId'],
          );
          /*
            $form['transitionId'.$outComes['targetName']] = array(
            '#type' => 'value',
            '#value' => $outComes['transitionId'],
            );
           */
        }
        $form['actionId'] = array(
          '#type' => 'value',
          '#value' => $list['actionId'],
        ); 
      }
    }
   
    if(!$editable && count($form['submit'])<4){
      unset($form['submit']);
    }
    
    //======================= end do actionList =============================
  } else {
    drupal_set_message($result['ResponseStatusInfo']['StatusMessage'], 'error');
  }

  return $form;
}

function _analyze_result($result) {

  if (isset($result['ResponseStatusInfo']) && $result['ResponseStatusInfo']) {
    $return = $result['ResponseStatusInfo']['StatusMessage'];
  } else {
    if ($http_code == 200) {
      $return = t('Start Process is successful.');
    } else if ($http_code == 700) {
      $return = t('Internal Server Error.');
    } else if ($http_code == 705) {
      $return = t('Access denied.');
    } else if ($http_code == 730) {
      $return = t('Bad Request JSON.');
    } else if ($http_code == 740) {
      $return = t('Invalid value [value] for [tagName].');
    }
  }
  return $return;
}

  /* [begin]add by kale @2013-02-20
 * get outcome data
 */

function get_action_outcome_from_wfe($node, $submission) { //print_r($node);die;
  global $user;
  if ($submission->is_draft == 1) {
    return;
  }
  $service = WORKFLOW_SERVICE_API . 'getActionOutcomes.ws';
 // $instance_info = get_instance_info($node, $submission);
  // if(empty($instance_info)){
  if (
          (!isset($node->wf_private_process_def_id) || empty($node->wf_private_process_def_id) ) ||
          (!isset($submission->instance_id) || empty($submission->instance_id) )
  ) {
    drupal_set_message(t('Submission start process failed, Please refresh current page.'), 'warning');
    if ($submission->is_draft == 0) {
      create_workflow_startProcess($node, $submission);
    }
    return;
  }
  $processInstanceId = $submission->instance_id;
  $wf_private_process_def_id = $node->wf_private_process_def_id;
  $condition = array('wf_private_process_def_id' => $wf_private_process_def_id);
  $userSwimlaneArray = get_swimlanes_by_role($user, $condition);

  $actionId = '';
  if (isset($_REQUEST['actionId']) && $_REQUEST['actionId']) {
    $actionId = $_REQUEST['actionId'];
  }

  $json_array = array();
  $json_array['userName'] = $user->name;
  $json_array['userSwimlaneKeys'] = implode(",", $userSwimlaneArray);
  $json_array['processInstanceId'] = $processInstanceId;
  $json_array['actionId'] = $actionId;
  $json = json_encode($json_array);
  //error_log('get_action_outcome:'.print_r($json,1));
  $api_result = call_workflow_service_api($service, $json);
  $result = json_decode($api_result['body'], true);
  //error_log('get_action_outcome:'.print_r($result,1));
  return $result;
}

/*
 * [end] by kale
 */



/*
 * [begin] add by kale@2013-02-20: judge weather a submission have permission to edit.
 */
function is_webform_submission_editable($node, $submission) {
  if (( isset($submission->is_draft) && $submission->is_draft == 1)) {
    return true;
  }
  $return = get_action_outcome_from_wfe($node, $submission);
  if (isset($return['actionList'][0]['editableFlag'])) {
    if ($return['actionList'][0]['editableFlag']) {
      return true;
    } else {
      drupal_set_message(t('Submission not allowed to edit.'));
      drupal_goto('node/' . $node->nid . '/submission/' . $submission->sid);
      //return false;
    }
  } else {
    //return true;//default to allow edit, maybe should change here
    if(defined('ENVIRONMENT') && ENVIRONMENT=='development'){
      return true;
    }
    else{
      return false;
    }
  }
}
/*
 * [end] by kale
 */